<template>
  <el-dialog
    v-model="dialogVisible"
    title="编辑需求"
    width="85%"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="edit-form"
      style="max-height: 65vh; overflow-y: auto"
    >
      <!-- 需求基本信息卡片 -->
      <el-card class="form-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>需求基本信息</span>
          </div>
        </template>
        <div class="form-row">
          <el-form-item label="需求名称" prop="name" class="form-item">
            <el-input v-model="form.name" maxlength="200" show-word-limit />
          </el-form-item>
          <el-form-item label="迭代版本" class="form-item">
            <el-input v-model="form.extend.iterativeVersion" maxlength="50" />
          </el-form-item>
          <!-- <el-form-item label="关联外部需求" prop="code" class="form-item">
            <el-input
              v-model="form.code"
              placeholder="JIRA编号等"
              maxlength="50"
            />
          </el-form-item> -->
        </div>

        <!-- <div class="form-row">
          <el-form-item label="优先级" prop="priority" class="form-item">
            <el-radio-group v-model="form.priority">
              <el-radio :label="1">低</el-radio>
              <el-radio :label="2">中</el-radio>
              <el-radio :label="3">高</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="状态" prop="status" class="form-item">
            <el-select
              v-model="form.status"
              placeholder="请选择状态"
              style="width: 100%"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </div> -->

        <!-- <div class="form-row">
          <el-form-item label="迭代版本" class="form-item">
            <el-input v-model="form.extend.iterativeVersion" maxlength="50" />
          </el-form-item>
        </div> -->
      </el-card>

      <!-- 需求任务列表卡片 -->
      <el-card class="form-card task-list-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>需求任务列表</span>
            <el-button
              type="primary"
              size="small"
              @click="addNewDemand"
              class="add-task-btn"
            >
              <el-icon><Plus /></el-icon> 添加任务
            </el-button>
          </div>
        </template>

        <div v-if="form.extend.newDemands.length === 0" class="empty-tasks">
          <el-empty description="暂无任务，请添加" />
        </div>

        <transition-group name="task-list" tag="div" class="task-list">
          <el-card
            v-for="(item, index) in form.extend.newDemands"
            :key="index"
            class="task-item"
            shadow="hover"
          >
            <template #header>
              <div class="task-header">
                <el-tag size="medium" effect="dark" class="task-number"
                  >任务 #{{ index + 1 }}</el-tag
                >
                <el-button
                  type="danger"
                  size="small"
                  circle
                  plain
                  @click="removeDemand(index)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </template>

            <div class="task-content">
              <div class="task-form-row">
                <el-form-item label="任务名称" class="task-form-item-full">
                  <el-input
                    v-model="item.demandName"
                    placeholder="请输入任务名称"
                    maxlength="100"
                  />
                </el-form-item>
              </div>

              <div class="task-form-row">
                <el-form-item label="需求描述" class="task-form-item-full">
                  <el-input
                    v-model="item.demandDescription"
                    placeholder="请输入需求描述"
                    type="textarea"
                    :rows="2"
                  />
                </el-form-item>
              </div>

              <div class="task-form-row three-columns">
                <el-form-item label="难度" class="task-form-item-equal">
                  <el-select
                    v-model="item.difficulty"
                    placeholder="请选择"
                    style="width: 100%"
                  >
                    <el-option label="简单" value="简单" />
                    <el-option label="中等" value="中等" />
                    <el-option label="复杂" value="复杂" />
                  </el-select>
                </el-form-item>
                <el-form-item label="预计时间" class="task-form-item-equal">
                  <div class="time-input-with-unit">
                    <el-input-number
                      v-model="item.expectedTime"
                      :min="0.5"
                      :max="20"
                      :step="0.5"
                      placeholder="天"
                      style="width: 100%"
                    />
                    <span class="time-unit">天</span>
                  </div>
                </el-form-item>
                <el-form-item label="时间范围" class="task-form-item-equal">
                  <el-date-picker
                    v-model="item.timeRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                    @change="(val) => handleDateRangeChange(item, val)"
                  />
                </el-form-item>
              </div>

              <div class="task-form-row two-columns">
                <el-form-item label="前端开发" class="task-form-item-equal">
                  <el-select
                    v-model="item.frontEndDeveloper"
                    placeholder="选择前端开发人员"
                    style="width: 100%"
                    filterable
                    @change="
                      (val) => handleTaskDeveloperSelect(item, 'frontend', val)
                    "
                  >
                    <el-option
                      v-for="dev in frontendDevelopers"
                      :key="dev.name"
                      :label="dev.name"
                      :value="dev.name"
                    >
                      <div class="developer-option">
                        <span>{{ dev.name }}</span>
                        <div class="tags">
                          <!-- 负责模块：绿色 -->
                          <div class="tag-group">
                            <el-tag
                              v-for="(skill, index) in dev.expertise"
                              :key="'skill-' + index"
                              size="small"
                              type="success"
                            >
                              {{ skill }}
                            </el-tag>
                          </div>

                          <!-- 技术栈：红色 -->
                          <div
                            class="tag-group"
                            v-if="
                              dev.technologyStack &&
                              dev.technologyStack.length > 0
                            "
                          >
                            <el-tag
                              v-for="(tech, index) in dev.technologyStack"
                              :key="'tech-' + index"
                              size="small"
                              type="danger"
                            >
                              {{ tech }}
                            </el-tag>
                          </div>

                          <!-- 能力等级：蓝色 -->
                          <div class="tag-group" v-if="dev.level">
                            <el-tag size="small" type="primary">
                              {{ dev.level }}
                            </el-tag>
                          </div>
                        </div>
                      </div>
                    </el-option>
                  </el-select>
                  <div
                    v-if="
                      item.frontEndDeveloperInfo?.expertise?.length ||
                      item.frontEndDeveloperInfo?.technologyStack?.length ||
                      item.frontEndDeveloperInfo?.level
                    "
                    class="selected-expertise"
                  >
                    <!-- 负责模块：绿色 -->
                    <div
                      v-if="item.frontEndDeveloperInfo?.expertise?.length"
                      class="tag-group"
                    >
                      <el-tag
                        v-for="(skill, index) in item.frontEndDeveloperInfo
                          .expertise"
                        :key="'skill-' + index"
                        size="small"
                        type="success"
                        class="expertise-tag"
                      >
                        {{ skill }}
                      </el-tag>
                    </div>

                    <!-- 技术栈：红色 -->
                    <div
                      v-if="item.frontEndDeveloperInfo?.technologyStack?.length"
                      class="tag-group"
                    >
                      <el-tag
                        v-for="(tech, index) in item.frontEndDeveloperInfo
                          .technologyStack"
                        :key="'tech-' + index"
                        size="small"
                        type="danger"
                        class="expertise-tag"
                      >
                        {{ tech }}
                      </el-tag>
                    </div>

                    <!-- 能力等级：蓝色 -->
                    <div
                      v-if="item.frontEndDeveloperInfo?.level"
                      class="tag-group"
                    >
                      <el-tag size="small" type="primary" class="expertise-tag">
                        {{ item.frontEndDeveloperInfo.level }}
                      </el-tag>
                    </div>
                  </div>
                </el-form-item>

                <el-form-item label="后端开发" class="task-form-item-equal">
                  <el-select
                    v-model="item.backEndDeveloper"
                    placeholder="选择后端开发人员"
                    style="width: 100%"
                    filterable
                    @change="
                      (val) => handleTaskDeveloperSelect(item, 'backend', val)
                    "
                  >
                    <el-option
                      v-for="dev in backendDevelopers"
                      :key="dev.name"
                      :label="dev.name"
                      :value="dev.name"
                    >
                      <div class="developer-option">
                        <span>{{ dev.name }}</span>
                        <div class="tags">
                          <!-- 负责模块：绿色 -->
                          <div class="tag-group">
                            <el-tag
                              v-for="(skill, index) in dev.expertise"
                              :key="'skill-' + index"
                              size="small"
                              type="success"
                            >
                              {{ skill }}
                            </el-tag>
                          </div>

                          <!-- 技术栈：红色 -->
                          <div
                            class="tag-group"
                            v-if="
                              dev.technologyStack &&
                              dev.technologyStack.length > 0
                            "
                          >
                            <el-tag
                              v-for="(tech, index) in dev.technologyStack"
                              :key="'tech-' + index"
                              size="small"
                              type="danger"
                            >
                              {{ tech }}
                            </el-tag>
                          </div>

                          <!-- 能力等级：蓝色 -->
                          <div class="tag-group" v-if="dev.level">
                            <el-tag size="small" type="primary">
                              {{ dev.level }}
                            </el-tag>
                          </div>
                        </div>
                      </div>
                    </el-option>
                  </el-select>
                  <div
                    v-if="
                      item.backEndDeveloperInfo?.expertise?.length ||
                      item.backEndDeveloperInfo?.technologyStack?.length ||
                      item.backEndDeveloperInfo?.level
                    "
                    class="selected-expertise"
                  >
                    <!-- 负责模块：绿色 -->
                    <div
                      v-if="item.backEndDeveloperInfo?.expertise?.length"
                      class="tag-group"
                    >
                      <el-tag
                        v-for="(skill, index) in item.backEndDeveloperInfo
                          .expertise"
                        :key="'skill-' + index"
                        size="small"
                        type="success"
                        class="expertise-tag"
                      >
                        {{ skill }}
                      </el-tag>
                    </div>

                    <!-- 技术栈：红色 -->
                    <div
                      v-if="item.backEndDeveloperInfo?.technologyStack?.length"
                      class="tag-group"
                    >
                      <el-tag
                        v-for="(tech, index) in item.backEndDeveloperInfo
                          .technologyStack"
                        :key="'tech-' + index"
                        size="small"
                        type="danger"
                        class="expertise-tag"
                      >
                        {{ tech }}
                      </el-tag>
                    </div>

                    <!-- 能力等级：蓝色 -->
                    <div
                      v-if="item.backEndDeveloperInfo?.level"
                      class="tag-group"
                    >
                      <el-tag size="small" type="primary" class="expertise-tag">
                        {{ item.backEndDeveloperInfo.level }}
                      </el-tag>
                    </div>
                  </div>
                </el-form-item>
              </div>
            </div>
          </el-card>
        </transition-group>
      </el-card>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, defineProps, defineEmits, watch, onMounted } from "vue";
import { Delete, Plus } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { task } from "@/utils/cueWords";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  taskData: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(["update:modelValue", "save"]);

const dialogVisible = ref(false);
const formRef = ref(null);

// 表单默认值
const defaultForm = {
  name: "",
  code: "",
  priority: 2,
  status: 1,
  extend: {
    iterativeVersion: "",
    frontEndDeveloper: {
      name: "",
      expertise: [],
    },
    backEndDeveloper: {
      name: "",
      expertise: [],
    },
    newDemands: [],
  },
};

const form = reactive({ ...defaultForm });

// 前后端技能选项
const frontendSkills = [
  "Vue",
  "React",
  "Angular",
  "JavaScript",
  "TypeScript",
  "HTML/CSS",
  "Webpack",
  "Vite",
];
const backendSkills = [
  "Java",
  "Python",
  "Node.js",
  "Go",
  "C#",
  "PHP",
  "Spring Boot",
  "Express",
  "Django",
];

// 开发人员数据
const frontendDevelopers = ref([]);
const backendDevelopers = ref([]);

// 初始化开发人员数据
onMounted(() => {
  try {
    // 直接使用task数据，不需要解析
    if (task && task.developers) {
      // 分离前端和后端开发人员
      frontendDevelopers.value = task.developers
        .filter((dev) => dev.job === "前端开发")
        .map((dev) => ({
          name: dev.name,
          expertise: dev.skills || [],
          technologyStack: dev.technologyStack || [],
          level: dev.level || "普通",
        }));

      backendDevelopers.value = task.developers
        .filter((dev) => dev.job === "后端开发")
        .map((dev) => ({
          name: dev.name,
          expertise: dev.skills || [],
          technologyStack: dev.technologyStack || [],
          level: dev.level || "普通",
        }));
    } else {
      throw new Error("开发人员数据不存在");
    }
  } catch (error) {
    console.error("处理开发人员数据失败:", error);
    // 兜底开发人员数据，确保包含cueWords.js中的所有开发人员
    frontendDevelopers.value = [
      {
        name: "王文权",
        expertise: ["告警详情", "告警列表"],
        technologyStack: ["vue", "javascript", "node"],
        level: "中级",
      },
      {
        name: "慈兆彤",
        expertise: ["视频管理", "AR大屏", "工作台管理系统"],
        technologyStack: ["vue", "javascript", "node"],
        level: "中级",
      },
      {
        name: "杨宽",
        expertise: ["视频管理", "AR大屏", "播放器"],
        technologyStack: ["vue", "javascript", "node"],
        level: "中级",
      },
      {
        name: "张瑞",
        expertise: [
          "视频管理",
          "AR大屏",
          "播放器",
          "工作台管理系统",
          "火势蔓延",
        ],
        technologyStack: ["vue", "javascript", "node"],
        level: "中级",
      },
      {
        name: "张佳美",
        expertise: ["地图搜索", "告警列表", "用户界面"],
        technologyStack: ["vue", "javascript", "css"],
        level: "中级",
      },
      {
        name: "张延雪",
        expertise: ["数据可视化", "通用管理", "组件库维护"],
        technologyStack: ["vue", "echarts", "typescript"],
        level: "初级",
      },
      {
        name: "张利庆",
        expertise: ["用户认证", "权限管理", "表单设计"],
        technologyStack: ["vue", "javascript", "element-plus"],
        level: "中级",
      },
      {
        name: "王小明",
        expertise: ["移动端适配", "播放器", "前端优化"],
        technologyStack: ["vue", "webpack", "sass"],
        level: "中级",
      },
      {
        name: "马文帅",
        expertise: ["AR大屏", "地图集成", "前端性能优化"],
        technologyStack: ["vue", "three.js", "webpack"],
        level: "初级",
      },
      {
        name: "吴飞",
        expertise: ["架构设计", "性能优化", "安全审计", "技术规范制定"],
        technologyStack: ["vue", "react", "angular", "typescript", "webpack"],
        level: "高级",
      },
    ];

    backendDevelopers.value = [
      {
        name: "易瑶",
        expertise: ["后端通用接口", "视频服务", "算法配置", "基础子平台服务"],
        technologyStack: ["java", "spring boot", "docker"],
        level: "中级",
      },
      {
        name: "胡恩德",
        expertise: ["后端通用接口", "视频服务", "算法配置", "基础子平台服务"],
        technologyStack: ["java", "spring boot", "docker"],
        level: "高级",
      },
      {
        name: "刘政铁",
        expertise: ["后端通用接口", "告警类", "火势类"],
        technologyStack: ["java", "spring boot", "docker"],
        level: "中级",
      },
      {
        name: "刘效廷",
        expertise: ["数据库优化", "微服务架构", "安全接口设计"],
        technologyStack: ["java", "spring cloud", "mysql", "redis"],
        level: "中级",
      },
    ];
  }
});

// 状态选项
const statusOptions = [
  { value: 1, label: "待处理" },
  { value: 2, label: "进行中" },
  { value: 3, label: "已完成" },
  { value: 4, label: "已取消" },
];

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "请输入需求名称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
  ],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
};

// 监听对话框显示状态
watch(
  () => props.modelValue,
  (val) => {
    dialogVisible.value = val;
    if (val && props.taskData) {
      // 深拷贝任务数据到表单
      const taskCopy = JSON.parse(JSON.stringify(props.taskData));

      // 确保扩展字段存在
      if (!taskCopy.extend) {
        taskCopy.extend = {};
      }
      if (!taskCopy.extend.frontEndDeveloper) {
        taskCopy.extend.frontEndDeveloper = { name: "", expertise: [] };
      }
      if (!taskCopy.extend.backEndDeveloper) {
        taskCopy.extend.backEndDeveloper = { name: "", expertise: [] };
      }
      if (!taskCopy.extend.newDemands) {
        taskCopy.extend.newDemands = [];
      }

      // 更新表单数据
      Object.assign(form, taskCopy);
    }
  }
);

// 监听对话框状态，同步到父组件
watch(
  () => dialogVisible.value,
  (val) => {
    emit("update:modelValue", val);
  }
);

// 添加新需求
const addNewDemand = () => {
  form.extend.newDemands.push({
    demandName: "",
    demandDescription: "",
    difficulty: "中等",
    expectedTime: 1,
    startTime: "",
    endTime: "",
    timeRange: [],
    frontEndDeveloper: "",
    backEndDeveloper: "",
    frontEndDeveloperInfo: {
      name: "",
      expertise: [],
    },
    backEndDeveloperInfo: {
      name: "",
      expertise: [],
    },
  });
};

// 移除需求
const removeDemand = (index) => {
  form.extend.newDemands.splice(index, 1);
};

// 处理日期范围变化
const handleDateRangeChange = (demand, val) => {
  if (val && val.length === 2) {
    [demand.startTime, demand.endTime] = val;
  } else {
    demand.startTime = "";
    demand.endTime = "";
  }
};

// 处理任务开发人员选择
const handleTaskDeveloperSelect = (demand, type, value) => {
  // 根据类型更新开发人员信息
  if (type === "frontend") {
    const selectedDeveloper = frontendDevelopers.value.find(
      (dev) => dev.name === value
    );
    if (selectedDeveloper) {
      // 使用对应的开发人员数据更新任务的开发人员信息
      demand.frontEndDeveloperInfo = {
        name: selectedDeveloper.name,
        expertise: selectedDeveloper.expertise,
        technologyStack: selectedDeveloper.technologyStack,
        level: selectedDeveloper.level,
      };
    } else {
      demand.frontEndDeveloperInfo = {
        name: value,
        expertise: [],
        technologyStack: [],
        level: "",
      };
    }
  } else if (type === "backend") {
    const selectedDeveloper = backendDevelopers.value.find(
      (dev) => dev.name === value
    );
    if (selectedDeveloper) {
      // 使用对应的开发人员数据更新任务的开发人员信息
      demand.backEndDeveloperInfo = {
        name: selectedDeveloper.name,
        expertise: selectedDeveloper.expertise,
        technologyStack: selectedDeveloper.technologyStack,
        level: selectedDeveloper.level,
      };
    } else {
      demand.backEndDeveloperInfo = {
        name: value,
        expertise: [],
        technologyStack: [],
        level: "",
      };
    }
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  // 先验证每个任务是否至少选择了一个开发人员
  let developerMissing = false;
  let missedTaskIndex = -1;

  if (form.extend.newDemands.length > 0) {
    for (let i = 0; i < form.extend.newDemands.length; i++) {
      const task = form.extend.newDemands[i];
      if (!task.frontEndDeveloper && !task.backEndDeveloper) {
        developerMissing = true;
        missedTaskIndex = i;
        break;
      }
    }
  }

  // 如果有任务缺少开发人员，显示错误并返回
  if (developerMissing) {
    ElMessage.error(
      `任务 #${
        missedTaskIndex + 1
      } 未选择任何开发人员，请至少选择一个前端或后端开发人员`
    );
    return;
  }

  // 继续验证表单其他字段
  await formRef.value.validate((valid) => {
    if (valid) {
      emit("save", JSON.parse(JSON.stringify(form)));
      dialogVisible.value = false;
    } else {
      ElMessage.error("请完善表单信息");
      return false;
    }
  });
};

// 对话框关闭时重置表单
const handleClosed = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
};
</script>

<style scoped lang="scss">
.edit-form {
  .form-card {
    margin-bottom: 16px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: bold;
      font-size: 16px;
    }

    .form-row {
      display: flex;
      gap: 20px;
      margin-bottom: 16px;

      .form-item {
        flex: 1;
      }
    }
  }

  .task-list-card {
    .add-task-btn {
      display: flex;
      align-items: center;
      gap: 4px;
    }

    .empty-tasks {
      padding: 30px 0;
    }

    .task-list {
      display: flex;
      flex-direction: column;
      gap: 20px;
    }

    .task-item {
      margin-bottom: 16px;
      border-left: 3px solid var(--el-color-primary);
      overflow: hidden;

      .task-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .task-number {
          font-weight: bold;
        }
      }

      .task-content {
        padding: 5px;

        .task-form-row {
          display: flex;
          gap: 16px;
          margin-bottom: 12px;
          width: 100%;

          &.three-columns {
            .task-form-item-equal {
              flex: 1;
              min-width: 0;

              :deep(.el-form-item__content) {
                width: 100%;
                display: flex;

                .el-select,
                .el-date-editor,
                .time-input-with-unit {
                  width: 100% !important;
                  flex: 1;
                }
              }
            }
          }

          &.two-columns {
            .task-form-item-equal {
              flex: 1;
              min-width: 0;

              .selected-expertise {
                display: flex;
                flex-wrap: wrap;
                gap: 4px;
                margin-top: 5px;

                .expertise-tag {
                  margin: 0;
                }
              }
            }
          }

          .task-form-item-full {
            flex: 1;
            width: 100%;

            :deep(.el-form-item__content) {
              width: 100%;
            }
          }
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.time-input-with-unit {
  display: flex;
  align-items: center;
  width: 100%;

  :deep(.el-input-number) {
    width: 100%;
  }

  .time-unit {
    margin-left: 5px;
    color: #606266;
    white-space: nowrap;
    font-size: 14px;
  }
}

.developer-option {
  display: flex;
  flex-direction: column;
  gap: 5px;

  .tags {
    display: flex;
    flex-direction: column;
    gap: 4px;

    .tag-group {
      display: flex;
      flex-wrap: wrap;
      gap: 4px;
      margin-bottom: 2px;
    }
  }
}

.selected-expertise {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-top: 5px;

  .expertise-tag {
    margin: 0;
  }
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-date-editor) {
  width: 100% !important;
}

:deep(.el-date-editor.el-input) {
  width: 100%;
}

:deep(.el-input-number) {
  width: 100%;
}

// 动画效果
.task-list-enter-active,
.task-list-leave-active {
  transition: all 0.3s ease;
}

.task-list-enter-from,
.task-list-leave-to {
  opacity: 0;
  transform: translateY(30px);
}
</style>
